﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using Microsoft.Practices.Unity;
using MiniStock.BusinessLogic.QueryLogic.Stock;
using MiniStock.Entities;
using MiniStock.Entities.Common.Query;
using MiniStock.Entities.Stock;
using MiniStock.Infrastructure;

namespace MiniStock.ServiceFacade.Stock
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class StockServiceFacade: IStockServiceFacade
    {
        private StockQueryLogic _stockQueryLogic = null;
        StockQueryLogic StockQueryLogic
        {
            get
            {
                if (_stockQueryLogic == null)
                {
                    lock (this)
                    {
                        if (_stockQueryLogic == null)
                            _stockQueryLogic = MiniStockContext.Current.RootContainer.Resolve<StockQueryLogic>();
                    }
                }

                return _stockQueryLogic;
            }
        }

        #region IServiceFacade Members

        public Customer GetCustomer(Guid id)
        {
            using (var c = new MiniStockContextScope())
            {
                return StockQueryLogic.GetCustomer(id);
            }
        }

        public List<Customer> ListCustomers(QueryToken query)
        {
            using (var c = new MiniStockContextScope())
            {
                if (query == null) query = new QueryToken();
                return StockQueryLogic.ListCustomers(query.Query, query.OrderBy, query.PageSize, query.PageIndex);
            }
        }

        public Product GetProduct(Guid id)
        {
            using (var c = new MiniStockContextScope())
            {
                return StockQueryLogic.GetProduct(id);
            }
        }

        public List<Product> ListProducts(QueryToken query)
        {
            using (var c = new MiniStockContextScope())
            {
                if (query == null) query = new QueryToken();
                return StockQueryLogic.ListProducts(query.Query, query.OrderBy, query.PageSize, query.PageIndex);
            }
        }

        public Order GetOrder(Guid id)
        {
            using (var c = new MiniStockContextScope())
            {
                return StockQueryLogic.GetOrder(id);
            }
        }

        public List<Order> ListOrders(QueryToken query)
        {
            using (var c = new MiniStockContextScope())
            {
                if (query == null) query = new QueryToken();
                return StockQueryLogic.ListOrders(query.Query, query.OrderBy, query.PageSize, query.PageIndex);
            }
        }

        #endregion
    }
}
